package com.woniuxy.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.admin.entity.AdminAccount;
import com.woniuxy.admin.entity.AdminInfo;
import com.woniuxy.admin.exception.AdminException;
import com.woniuxy.admin.entity.AdminAccountRole;
import com.woniuxy.admin.entity.AdminRole;
import com.woniuxy.admin.mapper.AdminAccountMapper;
import com.woniuxy.admin.mapper.AdminAccountRoleMapper;
import com.woniuxy.admin.mapper.AdminInfoMapper;
import com.woniuxy.admin.mapper.AdminRoleMapper;
import com.woniuxy.admin.service.AdminAccountRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.redis.util.RedisKey;
import com.woniuxy.redis.util.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ...
 * @since 2024年05月22日
 */
@Service
public class AdminAccountRoleServiceImpl extends ServiceImpl<AdminAccountRoleMapper, AdminAccountRole> implements AdminAccountRoleService {


    @Resource
    private AdminRoleMapper adminRoleMapper;

    @Resource
    private AdminAccountMapper adminAccountMapper;
    @Resource
    private AdminInfoMapper adminInfoMapper;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 绑定账号角色关系
     * @param accountId 账号Id
     * @param roleId 角色Id
     */
    @Override
    public void bindingAdminRole(Integer accountId, Integer roleId) {
        AdminAccount adminAccount = adminAccountMapper.selectById(accountId);
        if(adminAccount==null) throw new AdminException(10001,"账号不存在");
        List<AdminRole> adminRoles = adminRoleMapper.selectList(new QueryWrapper<>());
        if(adminRoles==null&&adminRoles.size()==0){
            throw new AdminException(10007,"请先添加角色");
        }
        AdminInfo adminInfo = adminInfoMapper.selectOne(new QueryWrapper<AdminInfo>().eq("account_id", accountId));
        if(adminInfo==null) throw new AdminException(10007,"请先完善个人信息");
        //查询所有角色 如果不存在参数角色Id 抛出异常
      if(!adminRoles.stream().map(a->a.getRoleId()).collect(Collectors.toList()).contains(roleId)) throw new AdminException(10008,"角色不存在");
        QueryWrapper<AdminAccountRole>wrapper=new QueryWrapper<>();
        wrapper.eq("account_id",accountId);
        AdminAccountRole adminAccountRole = this.getOne(wrapper);
        if(adminAccountRole==null){
            AdminAccountRole adminAccountRole1 = new AdminAccountRole();
            adminAccountRole1.setAccountId(accountId);
            adminAccountRole1.setRoleId(roleId);
            this.save(adminAccountRole1);
        }else {
           throw new AdminException(10001,"该账号已绑定角色");
        }
        if(roleId==5){
        redisUtil.zadd(RedisKey.jiandingshi(),accountId+"",0);
        }
        if(roleId==6){
        redisUtil.zadd(RedisKey.pinggushi(),accountId+"",0);
        }
    }
}
